require 'rake'
require 'rake/tasklib'
require File.dirname(__FILE__) + '/../facades'
require File.dirname(__FILE__) + '/../dotnet/framework'

module Rubicant::Tasks
  class CscTask < Rake::TaskLib

    attr_reader :name
    attr_accessor :target, :references, :out, :files, :debug

    def initialize(name)
      @name = name
      @csc = "#{Rubicant::DotNet::Frameworks.get_framework.framework_dir}\\csc.exe"
      yield self if block_given?
      define
    end

    def define
      fail ('Debug can only be true or nil') if (@debug.nil? == false && !@debug)
      task name do
        Rubicant::Runner.run "#{build_command}"
      end
      self
    end

    private
    def build_command
      build_rsp
      command = "#{@csc} @#{ENV['TEMP']}/csc.rsp"
      #puts command
      command
    end

    def build_rsp
      file = File.new("#{ENV['TEMP']}/csc.rsp", "w")

      file.puts " /target:#{@target}" unless @target.nil?
      file.puts " /reference:#{@references.join(';')}" unless @references.nil?
      file.puts " /out:#{@out}" unless @out.nil?
      file.puts " /debug:full" unless @debug.nil?
      file.puts " #{@files.to_a.join(' ')}".gsub(/\//, "\\") unless @files.nil?
      file.close

    end

  end

end

